package com.solar.etl.connector.sql;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import com.solar.etl.config.EtlBean;
import com.solar.etl.config.mapping.DataSet;
import com.solar.etl.config.mapping.Field;
import com.solar.etl.config.mapping.FieldSet;
import com.solar.etl.db.ResultQuery;
import com.solar.etl.db.SqlHelp;
import com.solar.etl.spi.ReadLineTokenizer;
import com.solar.etl.spi.WriteLineTokenizer;

public class DbLineTokenizer implements ReadLineTokenizer ,WriteLineTokenizer{
	public DbLineTokenizer(){}
	private Connection conn;
	private List<String> names;
	private String sql;
	private String tableName;
	private ResultQuery rq;
	private EtlBean mapping;
	
	public DbLineTokenizer(Connection conn,String sql){
		this.sql=sql;
		rq=SqlHelp.query(conn, sql);
	}
	
	public DbLineTokenizer(Connection conn,String tableName, String x){
		this.conn=conn;
		this.tableName=tableName;
	}
	@Override
	public void writeInit(EtlBean mapping) {
		this.mapping=mapping;
	}
	@Override
	public synchronized DataSet next() {
		DataSet dataSet=null;
		try {
			ResultSetMetaData rsData = rq.getResultSet().getMetaData();
			if(names==null){
				names=new ArrayList<String>();
				for (int i = 0; i < rsData.getColumnCount(); i++) {
					names.add(rsData.getColumnName(i+1));//锟斤拷锟斤拷锟�
				}
			}
			String[] values=new String[rsData.getColumnCount()];
			if(!rq.getResultSet().next()){
				return null;
			}
			for (int i = 0; i < rsData.getColumnCount(); i++) {
				values[i]=rq.getResultSet().getString(i+1);
			}
			dataSet =new DataSet(names,values);

		} catch (SQLException e) {
			e.printStackTrace();
		}
		return dataSet;
	}

	@Override
	public void writeLine(FieldSet fieldSet) {
		boolean flag=true;
		boolean sqlflag=true;

		//查询
		StringBuffer selectSql=new StringBuffer();
		StringBuffer whereSql=new StringBuffer();
		String[] seNames=new String[fieldSet.fields.size()];//where 条件查询的字段名称
		int n1=-1;
		selectSql.append("SELECT ");
		for (int j = 0; j < fieldSet.fields.size(); j++) {
			Field field=fieldSet.fields.get(j);
			if(sqlflag){
				sqlflag=false;
				selectSql.append(field.destName);
			}else{
				selectSql.append(",").append(field.destName);
			}
			if(null!=field.stype&&!"".equals(field.stype)){
				if(flag){
					flag=false;
					whereSql.append(field.destName).append("=? ");
					seNames[++n1]=field.destName;
				}else{
					whereSql.append(" AND ").append(field.destName).append("=?");
					seNames[++n1]=field.destName;
				}
			}
		}
		if(!"".equals(whereSql.toString())){
			selectSql.append(" FROM ").append(this.tableName+" WHERE ").append(whereSql.toString());
//			System.out.println(selectSql.toString());
			ResultQuery rq=SqlHelp.query(conn, selectSql.toString(), fieldSet, seNames);
			ResultSet rs= rq.getResultSet();
			try {
				if(rs!=null&&rs.next()){
					flag=false;
				}else{
					flag=true;
				}
			} catch (SQLException e) {
				e.printStackTrace();
			}
			rq.free();
		}

		if(flag){
			//新增
			StringBuffer sb=new StringBuffer();
			sb.append("INSERT INTO ").append(this.tableName);
			sb.append(" (");
			StringBuffer sbf=new StringBuffer();
			for (int i = 0; i < fieldSet.fields.size(); i++) {
				Field field=fieldSet.fields.get(i);
				sb.append(field.destName);
				if(field.seq!=null){
					sbf.append(field.seq).append(".nextval");
				}else{
					sbf.append("?");
				}
				if((fieldSet.fields.size()-1)!=i){
					sb.append(" ,");
					sbf.append(" ,");
				}
			}
			sb.append(") VALUES (").append(sbf.toString()).append(")");
			
//			System.out.println(sb.toString());
			SqlHelp.operate(conn, sb.toString(), fieldSet);
		}else{
			//更新
			flag=true;
			StringBuffer updateSql=new StringBuffer();
			String[] upNames=new String[fieldSet.fields.size()];
			int n2=-1;
			updateSql.append("UPDATE ").append(this.tableName).append(" SET ");
			for (int j = 0; j < fieldSet.fields.size(); j++) {
				Field field=fieldSet.fields.get(j);
				if(null==field.stype||"".equals(field.stype)){
					if(flag){
						flag=false;
						updateSql.append(field.destName).append("=?");
						upNames[++n2]=field.destName;
					}else{
						updateSql.append(",").append(field.destName).append("=?");
						upNames[++n2]=field.destName;
					}
				}
			}
			updateSql.append(" WHERE ").append(whereSql.toString());
			int y=-1;
			for (int i = 0; i < upNames.length; i++) {
				if(null==upNames[i]||"".equals(upNames[i])){
					if(null!=seNames[++y]){
						upNames[i]=seNames[y];
					}else{
						break;
					}
				}
			}
//			System.out.println(updateSql.toString());
			SqlHelp.update(conn, updateSql.toString(), fieldSet, upNames);
		}
	}

	@Override
	public void writeDestroy() {
		
	}

	@Override
	public void readDestroy() {
		if(rq!=null){
			rq.free();
		}
	}

	@Override
	public void writefinish() {
	}

	@Override
	public void commit() {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void rollback() {
		// TODO Auto-generated method stub
		
	}

}
